package com.module.overview.ui.cardHistoryDetails

import android.view.Gravity
import android.view.View
import android.widget.Toast
import androidx.fragment.app.Fragment
import androidx.viewpager2.adapter.FragmentStateAdapter
import androidx.viewpager2.widget.ViewPager2
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.common.app.base.AppActivity
import com.common.app.core.RouterHub
import com.common.app.data.bean.CalendarDay
import com.common.app.data.bean.KeyBundle
import com.common.app.data.bean.overView.HistoryDetailsModel
import com.common.app.dialog.SelectCalendarDialog
import com.common.app.utls.HeadTitleUtils
import com.common.app.utls.TimeUtils
import com.common.app.widget.calendardialog.CusCalendarView
import com.common.app.widget.calendardialog.CusCalendarViewDialog
import com.common.base.app.extras.postDelay
import com.common.base.app.extras.setOnClickListener
import com.common.base.app.extras.showToast
import com.common.base.utils.StatusBarUtils
import com.contrarywind.adapter.WheelAdapter
import com.contrarywind.listener.OnItemSelectedListener
import com.google.android.material.tabs.TabLayout
import com.google.android.material.tabs.TabLayoutMediator
import com.module.ble.utils.AllCardTypeConfig
import com.module.overview.R
import com.module.overview.databinding.OverviewActivityCardHistoryDetailsBinding
import java.util.Arrays
import java.util.Calendar


/**
 * 作者：sosou
 * <p>
 * 版本：1.0
 * <p>
 * 创建日期：2025/06/17
 * <p>
 * 描述：卡片信息详情页
 * <p>
 * 修订历史：
 */
@Route(path = RouterHub.ROUTER_OVERVIEW_CARD_HISTORY_DETAILS)
class CardHistoryDetailsActivity :
    AppActivity<OverviewActivityCardHistoryDetailsBinding, CardHistoryDetailsViewModel>(),
    View.OnClickListener, SelectCalendarDialog.OnSelectCalendarDialogListener {

    override fun getViewModel() = CardHistoryDetailsViewModel::class.java
    override fun getViewContentBinding() =
        OverviewActivityCardHistoryDetailsBinding.inflate(layoutInflater)

    override fun isShowToolBar(): Boolean = false
    override fun isStatusBarTranslate(): Boolean = true

    @Autowired(name = KeyBundle.BUNDLE_TITLE)
    @JvmField
    var mTitle: String? = null

    private val limitYears = 3 // 可以往前切换3年
    private val FRAGMENT_POOL_SIZE = 5
    private var VIRTUAL_COUNT = 10000 // 虚拟的大数量，支持向右无限滑动
    private var INITIAL_POSITION = VIRTUAL_COUNT / 2 // 初始位置在中间

    private var currentDateOffset = 0 // 当前日期偏移量（0表示今天，-1表示昨天）
    private val fragmentPool = mutableListOf<CardHistoryDetailsFragment>()
    private val fragmentMap = mutableMapOf<Int, CardHistoryDetailsFragment>() // 位置到Fragment的映射

    // 新增：用于同步ViewPager2和Wheel的flag，防止死循环
    private var isSyncingFromWheel = false
    private var isSyncingFromPager = false

    // days数据
    private val days = mutableListOf<CalendarDay>()

    // 获取单例实例
    private val calendarDialog by lazy { CusCalendarViewDialog.instance }
    private var selectedTimeMillis: Long = 0

    private val selectCalendarDialog by lazy { SelectCalendarDialog(this) }

    override fun initViews() {
        super.initViews()
        StatusBarUtils.setStatusBarHeight(mViewContentBinding.statusView)
        StatusBarUtils.setStatusBarForegroundColor(this, true)
        val headTitleUtils = HeadTitleUtils(this)
        headTitleUtils.setTitle(mTitle ?: "")
        headTitleUtils.setLineStyle(10)

        // 计算从startCalendar到当前系统时间的天数来设置虚拟的最大数量
        val currentCalendar = Calendar.getInstance()
        val diffInMillis = currentCalendar.timeInMillis - Calendar.getInstance().apply {
            set(Calendar.getInstance().get(Calendar.YEAR) - limitYears, 0, 1)
        }.timeInMillis
        VIRTUAL_COUNT = (diffInMillis / (24 * 60 * 60 * 1000)).toInt() * 2
        INITIAL_POSITION = VIRTUAL_COUNT / 2
        selectCalendarDialog.setLimitYears(limitYears)

        // 初始化Fragment池
        initFragmentPool()

        // 生成days数据，和ViewPager2页数一致
        days.clear()
        for (i in 0..INITIAL_POSITION) {
            val dateOffset = i - INITIAL_POSITION
            val temp = getDateString(dateOffset)
            days.add(getDateString(dateOffset))
            if (getString(R.string.common_today_hint) == temp.dateName) selectCalendarDialog.setCurDay(temp)
        }

        // 设置ViewPager2适配器
        mViewContentBinding.viewPager2.adapter = object : FragmentStateAdapter(this) {
            override fun getItemCount(): Int = days.size // 页数和days一致

            override fun createFragment(position: Int): Fragment {
                if (fragmentMap.containsKey(position)) {
                    return fragmentMap[position]!!
                }
                val dateOffset = position - INITIAL_POSITION
                val fragment = CardHistoryDetailsFragment.newInstance(getDateString(dateOffset), mTitle ?: "")
                fragmentMap[position] = fragment
                return fragment
            }

            override fun getItemId(position: Int): Long = position.toLong()
            override fun containsItem(itemId: Long): Boolean = itemId in 0 until itemCount
        }

        mViewContentBinding.viewPager2.layoutDirection = View.LAYOUT_DIRECTION_LTR
        mViewContentBinding.viewPager2.setCurrentItem(INITIAL_POSITION, false)

        mViewContentBinding.horizontalWheel.setOnItemSelectedListener { index ->
            if (isSyncingFromPager) return@setOnItemSelectedListener
            isSyncingFromWheel = true
            if (mViewContentBinding.viewPager2.currentItem != index) {
                mViewContentBinding.viewPager2.setCurrentItem(index, true)
                // 通过index直接获取days列表中对应的CalendarDay数据
                val selectedCalendarDay = days[index]
                selectedCalendarDay.isSelected=true
                selectCalendarDialog.setCurDay(selectedCalendarDay)
            }
            isSyncingFromWheel = false
        }

        // ViewPager2页面变化时同步horizontalWheel
        mViewContentBinding.viewPager2.registerOnPageChangeCallback(object :
            ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                val dateOffset = position - INITIAL_POSITION
                currentDateOffset = dateOffset
                // 如果试图滑动到未来时间，强制回到今天
                if (dateOffset > 0) {
                    mViewContentBinding.viewPager2.setCurrentItem(INITIAL_POSITION, true)
                    return
                }
                if (!isSyncingFromWheel) {
                    isSyncingFromPager = true
                    if (mViewContentBinding.horizontalWheel.currentItem != position) {
                        mViewContentBinding.horizontalWheel.setCurrentItem(position, true)
                    }
                    isSyncingFromPager = false
                }
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)
                if (state == ViewPager2.SCROLL_STATE_DRAGGING) {
                    val currentPosition = mViewContentBinding.viewPager2.currentItem
                    if (currentPosition >= INITIAL_POSITION) {
                        mViewContentBinding.viewPager2.isUserInputEnabled = false
                        mViewContentBinding.viewPager2.post {
                            mViewContentBinding.viewPager2.isUserInputEnabled = true
                        }
                    }
                }
            }
        })


        when (mTitle) {
            getString(R.string.common_sleep_hint) -> mViewModel.fieldNames = arrayOf("hasSleepInfo")
        }


        mViewModel.initFindByFieldEqualsOneQueryFlowRo()
    }

    private fun initFragmentPool() {
        fragmentPool.clear()
        fragmentMap.clear()
        // 预创建Fragment池，但不直接使用，而是作为模板
        repeat(FRAGMENT_POOL_SIZE) {
            fragmentPool.add(CardHistoryDetailsFragment.newInstance(null, mTitle ?: ""))
        }
    }

    private fun getDateString(dayOffset: Int): CalendarDay {
        val calendar = Calendar.getInstance()
        calendar.add(Calendar.DAY_OF_YEAR, dayOffset)

        val dateName = when (dayOffset) {
            0 -> getString(R.string.common_today_hint)
            else -> {
                val month = calendar.get(Calendar.MONTH) + 1
                val day = calendar.get(Calendar.DAY_OF_MONTH)
                "${month}月${day}日"
            }
        }

        return CalendarDay(
            year = calendar.get(Calendar.YEAR),
            month = calendar.get(Calendar.MONTH),
            day = calendar.get(Calendar.DAY_OF_MONTH),
            isCurrentMonth = false,
            isToday = dayOffset == 0,
            dateName = dateName,
            mCalendar = calendar
        )
    }

    override fun initEvents() {
        super.initEvents()

        mViewModel.allHeartEntryTimeList?.observe(this) {allHeartEntryTimeListIt->
            allHeartEntryTimeListIt.size
            val mDateStrList = mutableListOf<String>()
            allHeartEntryTimeListIt.forEach {
                mDateStrList.add(it.createdTime)
            }
            selectCalendarDialog.setHasEventDayList(mDateStrList)
        }
        selectCalendarDialog.setListener(this)
        mViewContentBinding.imgCalendar.setOnClickListener(onClick = this)
    }

    override fun lazyInitData() {
        super.lazyInitData()
        setupHorizontalWheelData()
    }

    override fun onClick(v: View?) {
        when (v) {
            mViewContentBinding.imgCalendar -> {
//                showCalendarDialog()
                selectCalendarDialog.show()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }

    private fun setupHorizontalWheelData() {
        // days数据已在initViews生成，这里只需设置适配器
        mViewContentBinding.horizontalWheel.setCyclic(false)
        mViewContentBinding.horizontalWheel.adapter = object : WheelAdapter<CalendarDay?> {
            override fun getItemsCount(): Int = days.size
            override fun getItem(index: Int): CalendarDay = days[index]
            override fun indexOf(o: CalendarDay?): Int = days.indexOf(o)
        }
        mViewContentBinding.horizontalWheel.setGravity(Gravity.BOTTOM)
        mViewContentBinding.horizontalWheel.setSelectRightMost(true)
        // 初始选中今天
        mViewContentBinding.horizontalWheel.currentItem = INITIAL_POSITION
    }


    private fun showCalendarDialog() {

        // 初始化对话框
        calendarDialog?.init(this)
            // 设置选中的日期（可选）
            ?.setSelectedDay(selectedTimeMillis)
            // 限制只显示两个月（可选）
            ?.setLimitMonth(false)
            // 添加标记日期（可选）
            ?.addMarks(getMarkedDays())
            // 显示对话框并设置日期点击监听器
            ?.show(object : CusCalendarView.OnCalendarClickListener() {
                override fun onDayClick(daySelectedCalendar: Calendar?) {
                    daySelectedCalendar?.let {
                        // 获取选中的日期时间戳
                        selectedTimeMillis = it.timeInMillis+5000
//                        mViewBinding.tvSleepTestData.text = "数据时间：${
//                            TimeUtils.getYearMonthDayHourMin(
//                                selectedTimeMillis
//                            )
//                        }"
//                        mViewModel.getTheDayData(selectedTimeMillis)
                        showToast("已选择日期: ${TimeUtils.getYearMonthDayHourMin(selectedTimeMillis)}")
                    }
                    // 关闭对话框
                    calendarDialog?.close()
                }

                override fun onDayNotMarkClick(daySelectedCalendar: Calendar?) {
                    daySelectedCalendar?.let {
                        selectedTimeMillis = it.timeInMillis+5000
//                        mViewBinding.tvSleepTestData.text = "数据时间：${
//                            TimeUtils.getYearMonthDayHourMin(
//                                selectedTimeMillis
//                            )
//                        }"
//                        mViewModel.getTheDayData(selectedTimeMillis)
                        // 点击了没有标记的日期
                        showToast("点击了没有标记的日期: ${TimeUtils.getYearMonthDayHourMin(it.timeInMillis)}")
                    }
                    // 关闭对话框
                    calendarDialog?.close()
                }

                override fun onLeftButtonClick() {
                    // 点击了左箭头按钮（上个月）
                }

                override fun onRightButtonClick() {
                    // 点击了右箭头按钮（下个月）
                }
            })
    }

    /**
     * 获取需要标记的日期列表
     */
    private fun getMarkedDays(): List<Long> {
        val markedDays = mutableListOf<Long>()

        // 示例：标记最近7天中的某些日期
        val calendar = Calendar.getInstance()

        // 标记今天
        markedDays.add(calendar.timeInMillis)

        // 标记前3天
        for (i in 1..3) {
            calendar.add(Calendar.DAY_OF_MONTH, -1)
            markedDays.add(calendar.timeInMillis)
        }

        return markedDays
    }

    override fun onSelectCalendarDialogClick(calendarDay: CalendarDay) {
//        showToast("选中日期: ${calendarDay.getDateString()}")

        // 计算选中日期与今天的偏移量
        val selectedCalendar = calendarDay.toCalendar()
        val todayCalendar = Calendar.getInstance()

        // 计算天数差
        val diffInMillis = selectedCalendar.timeInMillis - todayCalendar.timeInMillis
        val dayOffset = (diffInMillis / (24 * 60 * 60 * 1000)).toInt()

        // 检查是否选择了未来日期
        if (dayOffset > 0) {
            showToast("不能选择未来日期")
            return
        }

        // 计算目标位置
        val targetPosition = INITIAL_POSITION + dayOffset

        // 检查目标位置是否在有效范围内
        if (targetPosition >= 0 && targetPosition < days.size) {
            // 更新当前日期偏移量
            currentDateOffset = dayOffset

            // 切换ViewPager2到目标位置
            mViewContentBinding.viewPager2.setCurrentItem(targetPosition, true)

            // 同步更新horizontalWheel
            mViewContentBinding.horizontalWheel.setCurrentItem(targetPosition, true)
        } else {
            showToast("选择的日期超出可显示范围")
        }
    }

}